<template>
	<view class="page">
		<skeleton selector="skeleton" bgcolor="#FFFFFF" loading :show="showSkeleton"/>
		<view>
			<map subkey="WKHBZ-V5ZCU-7ODVC-BGXDB-HNV7J-KQBMP" layer-style="1" :polyline="polyline" :scale='scale' 
			:latitude="orderInfo.addressInfo.latitude" :longitude="orderInfo.addressInfo.longitude" :markers="covers"></map>
		</view>
		<view class="content skeleton">
			<view class="box">
				<view class="box" style="z-index: 10;height: auto;" :data-lastop="footerHeight" @touchstart="move.touchstart" @touchend="move.touchend" 
				@touchmove="move.touchmove">
					<uni-card :isFull="true" title="订单详情信息" isShadow>
						<view v-if="orderInfo.images.length>0" class="page-section-spacing">
							<swiper class="swiper" indicator-dots="true" autoplay="true" interval="5000" duration="1500">
								<swiper-item v-for="(item,index) in orderInfo.images" :key="index">
									<image @click="previewImage(orderInfo.images,index)" :src="item" mode="aspectFill"></image>
								</swiper-item>
							</swiper>
						</view>
						<uni-list>
							<uni-list-item class="skeleton-rect" title="订单类型:" :rightText="orderInfo.publicGive?'换取金钱':'公益赠送'" />
							<uni-list-item class="skeleton-rect" title="物品情况:"
								:rightText="orderInfo.garbageWeight?getWeightContent(orderInfo.garbageWeight)+'('+garbageType[orderInfo.garbageType].name+')':'加载中....'" />
							<uni-list-item class="skeleton-rect" title="预约时间:" :rightText="orderInfo.appointTime" />
						</uni-list>
					</uni-card>
				</view>
				
				<view>
					<uni-card :isFull="true" title="用户上门信息" isShadow>
						<uni-list>
							<uni-list-item class="skeleton-rect" title="客户名称:" :rightText="orderInfo.addressInfo.userName" />
							<uni-list-item class="skeleton-rect" title="联系手机:" v-if="orderInfo.addressInfo" :clickable="true" @click="callPhone">
								<template slot="footer">
									{{orderInfo.addressInfo.phone.replace(/^(\d{3})\d{4}(\d{4})$/,'$1****$2')}}
									<uni-icons type="phone" size="15" />
								</template>
							</uni-list-item>
							<uni-list-item class="skeleton-rect" :clickable="true" title="地址详情:" @click="toAddress">
								<template slot="footer">
									距离你{{orderInfo.distances.distance_str}}
									<uni-icons type="paperplane" size="15" />
								</template>
							</uni-list-item>
							<uni-list-item class="skeleton-rect" :clickable="true" :ellipsis="3" @click="toAddress"
								:title="orderInfo.addressInfo.locationAddress+orderInfo.addressInfo.addressDetail" />
						</uni-list>
					</uni-card>
					<uni-card title="回收结算信息" v-if="orderInfo.state==4" isShadow>
						<view v-if="orderInfo.checkImage.length>0" class="page-section-spacing">
							<swiper class="swiper" indicator-dots="true" autoplay="true" interval="5000" duration="1500">
								<swiper-item v-for="(item,index) in orderInfo.checkImage" :key="index">
									<image @click="previewImage(orderInfo.checkImage,index)" :src="item" mode="aspectFill"></image>
								</swiper-item>
							</swiper>
						</view>
						<uni-list>
							<uni-list-item title="实际总重量:" :rightText="orderInfo.weight" />
							<uni-list-item title="实际总支付:" :rightText="orderInfo.integral" />
							<uni-list-item title="结算时间:" :rightText="initDateTime()" />
						</uni-list>
					</uni-card>
					<button type="primary" v-if="orderInfo.state==0" @click="receivingOrders"
						style="background-color: #31b977;margin: 15px;">确认接单</button>
					<button type="primary" @click="inArrive"
						v-if="orderInfo.state==1&&orderInfo.receivingOrdersUserId==userInfo._id"
						style="background-color: #31b977;margin: 15px;">确认到达（提醒客户）</button>
						<button type="primary" @click="payOrder(orderInfo)"
							v-if="orderInfo.state==3&&orderInfo.receivingOrdersUserId==userInfo._id"
							style="background-color: #31b977;margin: 15px;">结算订单</button>
				</view>
			</view>
		</view>
		
	</view>
</template>
<script module="move" lang="wxs" src="../../common/adminmap.wxs"></script>
<script>
	import {
		getDistances,
		dateUtils
	} from '../../common/utils.js'
	var QQMapWX = require('../../common/qqmap-wx-jssdk.js')
	var demo = new QQMapWX({
		key: 'WKHBZ-V5ZCU-7ODVC-BGXDB-HNV7J-KQBMP'
	})
	import {
		mapGetters
	} from 'vuex'
	export default {
		computed: {
			...mapGetters({
				hasLogin: 'hasLogin',
				userInfo: 'userInfo'
			})
		},
		data() {
			return {
				timeOver: false,
				footerHeight: 0,
				showSkeleton:true,
				orderInfo: {},
				address: {},
				covers: [],
				dis:0,
				polyline:[],
				scale:13,
				latitude: 33.404659,
				longitude: 115.089099,
				garbageType: getApp().globalData.GarbageType
			}
		},
		onLoad(data) {
			this.orderInfo._id = data.id
		},
		mounted() {
			this.getFooterHeight();
		},
		onShow() {
			uni.getLocation({
				success: data => {
					this.longitude = data.longitude
					this.latitude = data.latitude
					this.$api("user-center", "updateUser", {
						locationInfo: data
					})
					this.initPage()
				}
			})
		},
		methods: {
			// 这里可以做一个scroll-y  的判断。 内部滚动
			changeHeight(val) {
				console.log(val)
				// if(val===true){
				// 	uni.navigateTo({
				// 		url:"order-desc"
				// 	})
				// }
			},
			getFooterHeight() {
				let query = wx.createSelectorQuery();
				query
					.select('.box')
					.boundingClientRect(res => {
						console.log(res);
						let height = res.height;
						this.footerHeight = res.height
					})
					.exec();
			},
			payOrder(item){
				uni.navigateTo({
					url:'pay-order?id='+item._id+'&orderType='+item.publicGive
				})
			},
			initDateTime(){
				return 	dateUtils.formatDateZh(new Date(this.orderInfo.settlementOrdersDateTime))
			},
			inArrive() {
				let distances = getDistances(this.latitude, this.longitude, this.orderInfo.addressInfo.latitude,
					this.orderInfo.addressInfo.longitude)
				console.log(distances)
				if (distances.distance >= 0.5) {
					uni.showModal({
						title: '提示',
						content: '距离定位' + distances.distance_str + ',已经超过500米确认到达么？',
						success: (re) => {
							if (re.confirm) {
								this.sendMsg()
								this.$api("recovery-order", "upd", {
									state: 2,
									_id: this.orderInfo._id
								}).then(res => {
									this.orderInfo.state = 2
									this.$msg("已提示用户已到达！")
								})
							}
						}
					})
				} else {
					this.sendMsg()
					this.$api("recovery-order", "upd", {
						state: 2,
						_id: this.orderInfo._id
					}).then(res => {
						this.orderInfo.state = 2
						this.$msg("已提示用户已到达！")
					})
				}
			},
			async initPage() {
				if(!getApp().globalData.GarbageType){
					let res=await this.$api("garbage", "getGarbageType")
					this.garbageType = res.data
					let temp = {}
					res.data.forEach(v => {
						temp[v._id] = v
					})
					getApp().globalData.GarbageType = temp
				}
				let res=await this.$api("recovery-order", "getById", {
					_id: this.orderInfo._id
				})
				this.orderInfo = res
				this.orderInfo.distances = getDistances(this.latitude, this.longitude, res.addressInfo
					.latitude, res.addressInfo.longitude)
				this.showSkeleton=false
				this.covers=[{
					width:30,
					height:30,
					callout: {
						content: "用户"+this.orderInfo.addressInfo.userName+"距您"+this.orderInfo.distances.distance_str,
						color:"#1aad19",
						borderRadius:20,
						padding:15,
						display:"ALWAYS"
					},
					label:{content:"距您"+this.orderInfo.distances.distance_str,color:"#1aad19"},
					latitude: this.orderInfo.addressInfo.latitude,
					longitude: this.orderInfo.addressInfo.longitude,
					iconPath: '../../static/mainPeo.png',
				}]
				this.covers.push({
					width:30,
					height:30,
					latitude: this.latitude,
					label:{content:"自己当前位置",color:"#1aad19"},
					longitude: this.longitude,
					iconPath: '../../static/somePeo.png',
				})
				let vm = this;
				//只测试距离使用 calculateDistance
				demo.direction({
					mode:'bicycling', //可选值：'driving'（驾车）、'walking'（步行）、'bicycling'（骑行），不填默认：'driving',可不填
					//from参数不填默认当前地址
					from:this.orderInfo.addressInfo.latitude+','+this.orderInfo.addressInfo.longitude,
					to: this.latitude+","+this.longitude,
					success: res => {
						console.log(res)
						let ret = res;
						let coors = ret.result.routes[0].polyline;
						let distance = ret.result.routes[0].distance;
						if(distance>1000){
							vm.dis = (distance/1000).toString().substr(0,3)+"km"
						}else{
							vm.dis = distance+"m"
						}
						
						if(distance>100000){
							vm.scale = 4
						}else  if(distance>60000){
							vm.scale = 6
						}else if(distance>20000){
							vm.scale = 8
						}else if(distance>10000){
							vm.scale = 11
						}else if(distance>5000){
							vm.scale = 12
						}else if(distance>1000){
							vm.scale = 13
						}
						let pl = [];
						let kr = 1000000;
						//坐标解压（返回的点串坐标，通过前向差分进行压缩）
						for (var i = 2; i < coors.length; i++) {
							coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
						}
						//将解压后的坐标放入点串数组pl中
						for (var i = 0; i < coors.length; i += 2) {
							pl.push({
								latitude: coors[i],
								longitude: coors[i + 1]
							})
						}
						vm.latitude = pl[0].latitude
						vm.longitude = pl[0].longitude
						vm.polyline = [{
							points: pl,
							color: '#1aad19',
							width: 4
						}]
						let tops = pl[pl.length-1]
					}
				})
			},
			receivingOrders() {
				if (this.userInfo.authenticationState!=2) {
					uni.showModal({
						title: '提示',
						content: '请先认证回收员！',
						success: () => {
							uni.navigateTo({
								url: '../user/userinfo'
							})
						}
					})
				} else {
					this.$api("recovery-order", "receivingOrders", this.orderInfo).then(res => {
						if (res) {
							this.orderInfo.state = 1 //已经接单
							this.orderInfo.receivingOrdersUserId=this.userInfo._id
							uni.showModal({
								title: "提示",
								content: '接单成功，是否导航。',
								success: (re) => {
									if (re.confirm) {
										this.toAddress()
									}
								}
							})
						} else {
							this.$msg("手慢了～此订单已被别人抢走了。。")
						}
					})
				}
			},
			async sendMsg() {
				let openid = await this.$api('user-center', 'getUserOpenIdById', {
					_id: this.orderInfo.user_id
				})
				let {
					result
				} = await this.$api('sendSubscribeMessage', 'subscribeMessage', {
					openid: openid,
					template_id: 'aPItP2S5Ia6W5CqHD_CO2UK7A8XX2zGnHrJR9yuzKNc',
					page: 'pages/order/order-desc?id=' + this.orderInfo._id,
					subscribeData: {
						thing15: {
							value: this.userInfo.authentication.nickName
						},
						phone_number16: {
							value: this.userInfo.authentication.mobile
						},
						time2: {
							value: dateUtils.formatDateZh(new Date())
						},
						thing3: {
							value: this.orderInfo.addressDesc.substr(0, 15) + '...'
						},
						thing4: {
							value: '回收员已经确认到达。。'
						}
					}
				})
			},
			getWeightContent(weight) {
				switch (weight) {
					case "1":
						return "10-50公斤"
						break;
					case "2":
						return "50-100公斤"
						break;
					case "3":
						return "100公斤以上"
						break;
				}
			},
			//预览图片
			previewImage(list, index) {
				uni.previewImage({
					current: index,
					urls: list,
				});
			},
			callPhone() {
				uni.makePhoneCall({
					phoneNumber: this.orderInfo.addressInfo.phone //仅为示例
				});
			},
			toAddress() {
				uni.openLocation({
					longitude: this.orderInfo.addressInfo.longitude,
					latitude: this.orderInfo.addressInfo.latitude
				})
			}
		}
	}
</script>
<style lang="scss" scoped>
	@import '@/components/iview/mixin.scss';
	
	
	
	map {
		width: 100%;
		height: 75vh;
	}
	
	.content {
	        position: fixed;
	        box-shadow: 1px -3px 16px 0 rgba(0,0,0,.1);
	        border-radius: 20px 20px 0 0;
	        width: 100%;
	        bottom: 0;
			overflow: auto;
	        padding: 0;
	        z-index: 88;
	        text-align: center;
	        color: #FFFFFF;
	    }
	    .content::before{
	        content: '';
	        position: absolute;
	        width: 160rpx;
	        height: 8rpx;
	        border-radius: 8rpx;
	        background-color: #c1b9b9;
	        top: 16rpx;
	        margin-left: -80rpx;
	    }
	.box {
		height: calc(100vh - 70vh);
	}

	.page-section-spacing {
		width: 100%;
	}

	.swiper {
		height: 400upx;
		width: 100%;
	}

	// swiper-item 里面的图片高度
	swiper-item image {
		width: 100%;
		height: 400upx;
		border-radius: 20upx 20upx 0 0;
	}

	.page {
		height: 100%;

		.message {
			width: 100%;
			box-shadow: 0px 2upx 16upx 0px rgba(0, 0, 0, 0.06);
			position: fixed;
			top: 0px;
			background-color: #FFFFFF;

			&-title {

				padding-left: 30upx;
				padding-right: 30upx;

				&-span {
					height: 70upx;
					font-size: 50upx;
					font-family: PingFangSC-Medium, PingFang SC;
					font-weight: 600;
					color: rgba(34, 34, 34, 1);
					line-height: 70upx;
				}
			}

			&-tab {
				padding-left: 30upx;
				padding-right: 30upx;
				display: flex;

				&-item {
					&-badge {}
				}
			}
		}

		.message-tabs {
			background-color: #FFFFFF;
		}

		.message-content {
			margin-top: 75rpx;
			height: calc(100% - 280rpx);
			overflow-y: scroll;

			.message-card {
				display: flex;
				margin: 30upx 30upx 0;
				position: relative;
				width: calc(100% - 30px);

				&-topRight {
					position: absolute;
					right: 20upx;
					top: 30upx;
					width: 130upx;
					background: #F0AD4E;
					color: #FFFFFF;
					height: 36upx;
					line-height: 36upx;
					font-size: 26upx;
					text-align: center;
					border-radius: 12upx;
				}

				&-left {
					width: 70upx;
					height: 70upx;
					font-size: 32upx;
					display: inline-block;
					text-align: center;
					line-height: 70upx;
					border-radius: 50%;
					color: white;
					background: rgba(74, 134, 236, 1);
				}

				&-right {
					flex: 1;
					position: relative;
					padding: 22upx 22upx;
					border: 2upx solid #E3E7EB;
					border-radius: 12upx;
					width: calc(100% - 30px);

					&-arrow {
						position: absolute;
						width: 18upx;
						height: 39upx;
						left: -18upx;
						top: 60upx;
						z-index: 111;
						background-size: 100% 100%;

					}

					&-content {
						font-size: 30upx;
						font-family: PingFangSC-Regular, PingFang SC;
						font-weight: 400;
						color: rgba(34, 34, 34, 1);
						line-height: 42upx;
						display: flex;
						text-align: center;
						padding: 14upx 10upx 0px;

						&-item {
							flex: 1;
						}
					}

					&-btns {
						display: flex;
						position: relative;
						margin-top: 20upx;
						font-size: 32upx;
						font-weight: 400;
						color: rgba(34, 34, 34, 1);
						line-height: 60upx;
						padding-top: 15upx;
						padding-left: 20upx;
						padding-right: 20upx;

						&:after {
							@include hairline();
							border-top-width: 1px;
						}

						&-divider {
							width: 1upx;
							background: #E3E7EB;
							height: 48upx;
						}

						&-reject {
							flex: 1;
							display: flex;
							justify-content: center;

							&-btn {
								width: 200upx;
								background: #FF4259;
								border-radius: 10upx;
								color: #FFFFFF;
								text-align: center;
							}

						}

						&-agree {
							flex: 1;
							display: flex;
							justify-content: center;

							&-btn {
								width: 200upx;
								background: #31b977;
								border-radius: 10upx;
								color: #FFFFFF;
								text-align: center;
							}
						}
					}

					&-info {
						font-size: 28upx;
						font-weight: 400;
						color: rgba(153, 153, 153, 1);
						line-height: 40upx;

						&-time {
							display: inline-block;
							font-size: 28upx;
							font-weight: 400;
							color: rgba(34, 34, 34, 1);
						}
					}

					&-title {
						display: flex;

						// justify-content: space-between;
						align-items: center;

						&-left {
							font-size: 34upx;
							font-weight: 400;
							color: #222222;
							flex: 1;

							span {
								color: #4A86EC;
							}
						}

						&-right {
							font-size: 32upx;
							font-weight: 400;
							color: rgba(153, 153, 153, 1);
						}
					}
				}
			}
		}

	}
</style>
